const express = require('express');
const fs = require('fs');
const { type } = require('jquery');
const router = express.Router()

function readFile(url) {
    return new Promise(function (resolve, reject) {
        fs.readFile(url, 'utf8', function (err, data) {
            if (err) {
                return reject(err)
            }
            resolve(data)
        })
    })
}
function writeFile(data) {
    return new Promise((res, rej) => {
        fs.writeFile(data.path, data.data, data.options = { encoding: 'utf-8', mode: 0666, flag: 'w' }, function (err) {
            if (err) {
                rej(err)
            } else {
                res()
            }
        })
    })
}
function whoWins(arr, row, line, value) {
    //先找X轴左侧相邻且相同的最远距离
    let xLeftDistance = 0 //x轴左侧距离
    let xRightDistance = 0 //x轴右侧距离
    let yTopDistance = 0 //y轴上方距离
    let yBottomDistance = 0  //y轴下方距离
    let leftTop = 0 //左上距离 斜线距离
    let rightBottom = 0 // 右下距离
    let leftBottom = 0 //左下距离
    let rightTop = 0 //右上距离
    if (line == 0) {
        xLeftDistance = 0
    } else {
        for (let i = line; i > -1; i--) {
            xLeftDistance = line - i - 1
            if (arr[row][i] !== value) {
                break
            }
        }
    }
    console.log('xLeftDistance:' + xLeftDistance)
    //找x轴右侧相邻且相同的最远距离
    if (line === arr[row].length) {
        xRightDistance = 0
    } else {
        for (let i = line; i < arr[row].length; i++) {
            xRightDistance = i - line - 1
            if (arr[row][i] !== value) {
                break
            }
        }
    }
    console.log('xRightDistance:' + xRightDistance)
    if ((xRightDistance + xLeftDistance) > 3) {//  22  2   22   左边加右边保证大于3就行
        result = true
        winValue = value
        return true
    }

    //找y轴上方相邻且相同的最远距离
    if (row === 0) {
        yTopDistance = 0
    } else {
        for (let i = row; i > -1; i--) {
            yTopDistance = row - i - 1
            if (arr[i][line] !== value) {
                break
            }
        }
    }
    console.log('yTopDistance:' + yTopDistance)
    //找y轴下方相邻且相同的最远距离
    if (row === arr.length) {
        yBottomDistance = 0
    } else {
        for (let i = row; i < arr.length; i++) {
            yBottomDistance = i - row - 1
            if (arr[i][line] !== value) {
                break
            }
        }
    }
    console.log('yBottomDistance:' + yBottomDistance)
    if ((yTopDistance + yBottomDistance) > 3) {//不解释
        result = true
        winValue = value
        return true
    }
    //寻找左上相邻且相同的最远距离
    if (row === 0 || line === 0) {
        leftTop = 0
    } else {
        let short;
        row > line ? (short = line) : (short = row)
        for (let i = 1; i < (short + 1); i++) {
            if (arr[row - i][line - i] !== value) {
                break
            }
            leftTop = i
        }
    }
    console.log('leftTop:' + leftTop)

    //寻找右下相邻且相同的最远距离
    let xLength = arr[0].length - 1
    let yLength = arr.length - 1
    if (xLength === line || yLength === row) {
        rightBottom = 0
    } else {
        let long
        (xLength - line) < (yLength - row) ? long = xLength - line : long = yLength - row
        for (let i = 0; i < (long + 1); i++) {
            if (arr[row + i][line + i] !== value) {
                break
            }
            rightBottom = i
        }
    }
    console.log('rightBottom:' + rightBottom)

    if ((leftTop + rightBottom) > 3) {//不解释
        result = true
        winValue = value
        return true
    }


    //寻找右上相邻且相同的最远距离
    if(xLength === line || row === 0){
        rightTop = 0
    }else{
        let long
        (xLength - line) < row ? long = xLength - line : long =  row
        for(let i = 0;i < (long +1);i++){
            if(arr[row-i][line+i] !== value){
                break
            }
            rightTop = i
        }
    }
    console.log('rightTop:'+rightTop)

    //寻找左下相邻且相同的最远距离
    if(row === yLength || line === 0){
        leftBottom = 0
    }else{
        let short
        line < (yLength- row) ? short = line : short = (yLength- row)
        for (let i = 0;i < short;i++){
            if(arr[row+i][line-i] !== value){
                break
            }
            leftBottom = i
        }
    }


    if ((leftBottom + rightTop) > 3) {//不解释
        result = true
        winValue = value
        return true
    }
    console.log('leftBottom:' + leftBottom)
    return false
}
let isBlackChess = true
let result = false
let winValue = undefined
router.post('/setData', (req, res) => {
    if (result) return res.send('已经有输赢结果了,' + '赢得value是:' + winValue)
    if (req.body.isBlackChess !== isBlackChess) return res.send('err')
    readFile('./data/index.json').then((data) => {
        let arr = JSON.parse(data)
        arr[req.body.row][req.body.line] = req.body.value
        whoWins(arr, req.body.row, req.body.line, req.body.value)
        writeFile({
            path: './data/index.json',
            data: JSON.stringify(arr)
        }).then(() => {
            isBlackChess = !isBlackChess
            console.log(isBlackChess)
            res.send('ok')
        })

    })
});



router.get('/', (req, res) => {

    readFile('./data/index.json').then((data) => {
        res.send({ list: data, isBlackChess ,winValue,result})
    }).catch(() => {
        return console.log('json读取失败')
    });
});


router.get('/del', (req, res) => {

    readFile('./data/index.json').then((data) => {
        let arr = JSON.parse(data)
        arr.forEach((item, row) => {
            item.forEach((item2, line) => {
                arr[row][line] = 0
            })
        });
        writeFile({
            path: './data/index.json',
            data: JSON.stringify(arr)
        }).then(() => {
            isBlackChess = true
            result = false
            winValue = undefined
            res.send('清除成功')
        })
    }).catch(() => {
        return console.log('json读取失败')
    });
});
module.exports = router
